package com.flyduck.vueshop.order.h5.service.impl;

import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.alipay.api.response.AlipayTradeWapPayResponse;
import com.flyduck.vueshop.common.core.exception.BusinessException;
import com.flyduck.vueshop.order.constant.OrderConstant;
import com.flyduck.vueshop.order.entity.AppOrder;
import com.flyduck.vueshop.order.h5.service.H5PayService;
import com.flyduck.vueshop.order.manager.AppOrderManager;
import com.flyduck.vueshop.order.manager.AppPayManager;
import com.flyduck.vueshop.order.mapper.AppOrderMapper;
import com.flyduck.vueshop.order.properties.AlipayProperties;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.time.LocalDateTime;
import java.util.Map;

/**
 * <p>
 * AppPayServiceImpl
 * </p>
 *
 * @author flyduck
 * @since 2024-05-22
 */
@Service
public class H5PayServiceImpl implements H5PayService {

    @Resource
    private AppOrderMapper appOrderMapper;
    @Resource
    private AppPayManager appPayManager;
    @Resource
    private AlipayProperties alipayProperties;
    @Resource
    private AppOrderManager appOrderManager;

    @Override
    public String orderPayByOrderSn(String orderSn) {
        AppOrder appOrder = appOrderManager.verifyAppOrderBySn(orderSn);

        AlipayTradeWapPayResponse alipayTradeWapPayResponse = appPayManager.alipay(appOrder);
        if(!alipayTradeWapPayResponse.isSuccess()){
            throw new BusinessException("支付失败，请稍后再试！");
        }
        return alipayTradeWapPayResponse.getBody();
    }

    @Override
    public void payNotify(Map<String, String> paramMap, HttpServletResponse response) throws IOException {
        PrintWriter writer = response.getWriter();

        //普通公钥模式验签，切记alipaypublickey是支付宝的公钥，请去open.alipay.com对应应用下查看。
        try {
            boolean flag = AlipaySignature.rsaCheckV1(paramMap, alipayProperties.getAlipayPublicKey(), "GBK","RSA2");
            if (flag) {
                //商户订单号
                String outTradeNo = paramMap.get("out_trade_no");
                //支付宝交易号
                String tradeNo = paramMap.get("trade_no");
                //交易状态
                String tradeStatus = paramMap.get("trade_status");
                if("TRADE_SUCCESS".equals(tradeStatus)){
                    AppOrder appOrder = appOrderMapper.getAppOrderBySn(outTradeNo);
                    //待支付 => 待发货
                    if (OrderConstant.OrderStatus.PENDING_PAYMENT.getCode() == appOrder.getOrderStatus()) {
                        appOrder.setOrderStatus(OrderConstant.OrderStatus.PENDING_DELIVERY.getCode());
                        appOrder.setPayTradeNo(tradeNo);
                        appOrder.setPayTime(LocalDateTime.now());
                        appOrderMapper.updateById(appOrder);
                        writer.print("success");
                    }
                }
            }else {
                writer.print("fail");
            }
        } catch (AlipayApiException e) {
            e.printStackTrace();
            writer.print("fail");
        }
        writer.flush();
        writer.close();
        writer = null;
    }

    @Override
    public String payCheckByOrderSn(String orderSn) {
        AppOrder appOrder = appOrderManager.verifyAppOrderBySn(orderSn);
        if(OrderConstant.OrderStatus.PENDING_DELIVERY.getCode() == appOrder.getOrderStatus()){
            //已经同步支付成功
            return "success";
        }

        AlipayTradeQueryResponse response = appPayManager.aliCheck(orderSn);
        if (response.isSuccess()) {
            if ("TRADE_SUCCESS".equals(response.getTradeStatus())) {
                appOrder.setOrderStatus(OrderConstant.OrderStatus.PENDING_DELIVERY.getCode());
                appOrder.setPayTradeNo(response.getTradeNo());
                appOrder.setPayTime(LocalDateTime.now());
                appOrderMapper.updateById(appOrder);
                return "success";
            }
        }
        return response.getSubMsg();
    }
}
